package io.github.veigara.tcp.framework.model;

/**
 * @author : zhouhx
 * @date : 2025/6/6 13:27
 */

import io.github.veigara.tcp.framework.DeviceServer;
import io.github.veigara.tcp.framework.protocol.ProtocolHandler;
import io.netty.channel.Channel;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 设备连接
 */
@Data
public class DeviceConnection {
    private static final Logger logger = LoggerFactory.getLogger(DeviceConnection.class);

    private final DeviceConnectionInfo deviceConnectionInfo;
    private final Channel channel;
    private final DeviceType deviceType;
    private final ProtocolHandler protocolHandler;
    private final DeviceServer deviceServer;


    public DeviceConnection(DeviceConnectionInfo deviceConnectionInfo, Channel channel, DeviceType deviceType,
                            ProtocolHandler protocolHandler, DeviceServer deviceServer) {
        this.deviceConnectionInfo = deviceConnectionInfo;
        this.channel = channel;
        this.deviceType = deviceType;
        this.protocolHandler = protocolHandler;
        this.deviceServer = deviceServer;
    }

    // 断开连接
    public void disconnect() {
        if (channel.isOpen()) {
            channel.close();
        }
        deviceServer.removeDeviceConnection(this.deviceConnectionInfo.getDeviceId());
    }

    // 发送消息,包级私有，不对外暴露
    public void sendMessage(Object message) {
        if (channel.isActive()) {
            channel.writeAndFlush(message).addListener(future -> {
                if (future.isSuccess()) {
                    logger.debug("Message sent successfully: {}", message);
                } else {
                    logger.error("Failed to send message: {}", message, future.cause());
                }
            });
        } else {
            logger.warn("Channel is not active, cannot send message");
        }
    }

    // 判断连接是否活跃
    public boolean isConnected() {
        return channel != null && channel.isActive();
    }
}
